import { getEndReportData, getStartReportData } from "@/utils/monitor";
import request, { statisticRequest } from "../utils/openApiRequest";
import configWifiModel from "../pages/configDevice/models/configWifi";

interface IQuery {
  did: string;
  startime: number;
  endtime: number;
  attr: string;
  aggregator: string;
  unit: string;
}

// eslint-disable-next-line import/prefer-default-export
export async function queryAggregate({
  did,
  startime,
  endtime,
  attr,
  aggregator,
  unit,
}: IQuery) {
  // eslint-disable-line
  const url = `app/devdata/${did}/agg_data?start_ts=${startime}&end_ts=${endtime}&attrs=${attr}&aggregator=${aggregator}&unit=${unit}`;
  const options = {
    method: "GET",
  };
  return request(url, options);
}

export async function reportStartConfigWifiEvent(monitorTarget: any) {
  const startData = getStartReportData(monitorTarget);
  const pk = configWifiModel.curPk;

  statisticRequest(`v2/products/${pk}/devices/dist-net`, {
    method: "POST",
    body: startData,
  }).then((res) => {
    if(res.success){
      console.log("===已上报开始配网事件===",pk,startData);
    }else{
      // cache startData
      configWifiModel.curStartData = startData;
    }
  });
}

export async function reportStopConfigWifiEvent({
  devices,
  paasRes,
  saasRes,
  sdkRes,
}: {
  devices: IDevice[];
  paasRes: any;
  saasRes: any;
  sdkRes: any;
}) {
  const pk = configWifiModel.curPk;
  if(configWifiModel.curStartData){
    // 开始配网事件上报失败，重新上报
    const res =  await statisticRequest(`v2/products/${pk}/devices/dist-net`, {
      method: "POST",
      body: configWifiModel.curStartData,
    })
    if(res.success){
      console.log("===重新上报开始配网事件成功===",pk,configWifiModel.curStartData);
    }else{
      console.log("===重新上报开始配网事件失败===",pk,configWifiModel.curStartData);
    }
  }

  const endData = getEndReportData(devices, paasRes, saasRes, sdkRes);
  
  statisticRequest(`v2/products/${pk}/devices/dist-net`, {
    method: "POST",
    body: endData,
  })
    .then((res) => {
      clearEventCache();
      if(res.success){
        console.log("===已成功上报结束配网事件===",pk,endData);
      }else{
        console.log("===上报结束配网事件失败===",pk,endData);
      }
      
    })
    .catch(clearEventCache);
}

function clearEventCache() {
  configWifiModel.sdkResCache = null;
  configWifiModel.eventID = null;
  configWifiModel.curPk = null;
  configWifiModel.curStartData = null;
}
